<?php

namespace app\controllers\admin\uni\finance;

use app\controllers\admin\base\AdminController;
use app\models\merchant\MerchantOrder as Model;

/**
 * Class MerchantController
 * @package app\controllers\admin\uni\finance
 */
class MerchantController extends AdminController
{
    public function actionList()
    {
        $sn = $this->post('sn');
        $user_id = $this->post('user_id');
        $export = $this->post('export');

        $start = $this->post('start');
        $end = $this->post('end');

        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $sort = $this->post('sort');

        $query = Model::find()
            // ->where(['status' => 1]);
            ->where(['>=', 'status', 1]);

        if ($sort) {
            $prop = substr($sort, 0, 1);
            $prop = $prop == '-' ? SORT_DESC : SORT_ASC;
            $order = substr($sort, 1);
            $query->orderBy([$order => $prop]);
        } else {
            $query->orderBy(['id' => SORT_DESC]);
        }

        if ($user_id) {
            $query->andWhere(['user_id' => $user_id]);
        }
        if ($sn) {
            $query->andWhere(['like', 'sn', $sn]);
        }

        // if ($start) {
        //     $query->andWhere(['>=', 'create_time', $start]);
        // }
        // if ($end) {
        //     $query->andWhere(['<=', 'create_time', $end]);
        // }
        if ($start) {
            // $query->andWhere(['>=', 'create_time', $start]);
            $query->andWhere(['>=', 'DATE_FORMAT(create_time, "%Y-%m-%d")', date('Y-m-d', strtotime($start))]);
        }
        if ($end) {
            // $query->andWhere(['<=', 'create_time', $end]);
            $query->andWhere(['<=', 'DATE_FORMAT(create_time, "%Y-%m-%d")', date('Y-m-d', strtotime($end))]);
        }

        // export
        if ($export) {
            $list = $query
                ->with(['merchant', 'payFor'])
                ->asArray()
                ->all();
            return $this->success($list);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->with(['merchant', 'payFor'])
            ->asArray()
            ->all();

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
        ]);

    }
}